
import { WsConnection } from "tsrpc";
import { ServiceType } from "../shared/protocols/serviceProto";
import { Room } from "../shared/Room";

export interface RoomServerOptions {
    port: number,
    thisServerUrl: string,
    matchServerUrl: string
}

export class RoomServer {

    rooms: Room[] = [];

    constructor() {
        // 定时清除闲置的房间
        setInterval(() => {
            this._clearIdleRooms();
        }, 20000);
    }
    private _nextRoomId = 1;
    /** 创建房间 */
    createRoom(): Room {
        let room = new Room(this._nextRoomId++);

        this.rooms.push(room);

        return room;
    }
    remove(conn: WsConnection<ServiceType>, roomeId: number): { isSucc: true } | { isSucc: false, errMsg: string } {
        let room = this.rooms.find(item => item.state.id === roomeId)
        try {
            room?.leave(conn)
            this._clearIdleRooms()
            return { isSucc: true }
        } catch (error) {
            return { isSucc: false, errMsg: '没有找到该房间' }
        }
    }
    join(conn: WsConnection<ServiceType>, roomeId?: number): { isSucc: true } | { isSucc: false, errMsg: string } {
        let room: Room | undefined
        
        // 有ID通过id查找房间
        if (roomeId) {
            room = this.rooms.find(item => item.state.id === roomeId)
        } else {
            // 随机加入房间
            room = this.rooms.find(item => !item.peopleIsFull())
        }
        if (room) {
            return room.join(conn)
        } else {
            return { isSucc: false, errMsg: '没有房间可加入' }
        }
    }
    /** 清除未开始的房间 */
    private _clearIdleRooms() {
        const now = Date.now();
        // 清除超过 5 秒没有开始的房间
        this.rooms.filter(v => v.state.status !== "start" && (v.state.lastEmptyTime && now - v.state.lastEmptyTime >= 10000)).forEach(room => {
            let index = this.rooms.findIndex(item => item.state.id === room.state.id)

            if (index > -1) {
                room.destroyed()
                this.rooms.splice(index, 1)
            }
        })


    }
}

